package com.techsoul.module.pms.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.techsoul.common.core.constant.ApiConstants;
import com.techsoul.common.core.exception.BusinessException;
import com.techsoul.common.core.exception.ExcelException;
import com.techsoul.common.core.pojo.vo.UserVo;
import com.techsoul.common.core.util.ServletUtils;
import com.techsoul.common.core.exception.ParamException;
import com.techsoul.common.core.util.bean.BeanUtils;
import com.techsoul.common.core.util.collection.ListUtils;
import com.techsoul.common.core.util.http.HttpClientUtils;
import com.techsoul.common.core.util.id.IdWorker;
import com.techsoul.common.core.util.lang.DateUtils;
import com.techsoul.common.core.util.lang.NumberUtils;
import com.techsoul.common.core.util.lang.StringUtils;
import com.techsoul.common.core.util.poi.ExcelImport;
import com.techsoul.common.security.service.TokenService;
import com.techsoul.module.basic.mapper.*;
import com.techsoul.module.basic.pojo.entity.*;
import com.techsoul.module.basic.pojo.param.SuspiciousItemSaveParam;
import com.techsoul.module.basic.pojo.vo.CustomerVo;
import com.techsoul.module.basic.pojo.vo.StoreVo;
import com.techsoul.module.basic.pojo.vo.SupplierVo;
import com.techsoul.module.goods.enmus.SpuStatusEnum;
import com.techsoul.module.goods.mapper.SkuMapper;
import com.techsoul.module.goods.mapper.SpuMapper;
import com.techsoul.module.goods.pojo.entity.Sku;
import com.techsoul.module.goods.pojo.entity.Spu;
import com.techsoul.module.goods.pojo.vo.SkuVo;
import com.techsoul.module.order.enmus.SalesOrderSourceEnum;
import com.techsoul.module.order.enmus.SalesOrderStatusEnum;
import com.techsoul.module.order.enmus.SalesOrderTypeEnum;
import com.techsoul.module.order.pojo.entity.PriceTrack;
import com.techsoul.module.order.pojo.entity.SalesOrder;
import com.techsoul.module.order.pojo.entity.SalesOrderItem;
import com.techsoul.module.order.pojo.vo.SalesOrderItemVo;
import com.techsoul.module.pms.enmus.WmsInStatusEnum;
import com.techsoul.module.pms.enmus.WmsOutStatusEnum;
import com.techsoul.module.pms.mapper.*;
import com.techsoul.module.pms.pojo.entity.*;
import com.techsoul.module.pms.pojo.param.*;
import com.techsoul.module.pms.pojo.vo.*;
import com.techsoul.module.pms.service.IBmsAllGeneralSeqTabService;
import com.techsoul.module.pms.service.ITbWmsMaterialDeliveryLineService;
import com.techsoul.module.pms.service.ITbWmsMaterialDeliveryService;
import com.techsoul.module.system.enmus.ErrorType;
import com.techsoul.module.system.mapper.OperationLogMapper;
import com.techsoul.module.system.pojo.entity.OperationLog;
import com.techsoul.module.system.service.IConfigService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 出库明细 Service实现
 *
 * @author liuen
 * @date 2022-01-25
 */
@Slf4j
@Service
@Transactional(readOnly = true)
public class TbWmsMaterialDeliveryLineServiceImpl implements ITbWmsMaterialDeliveryLineService {

    @Autowired
    private IdWorker idWorker;

    @Autowired
    private SuspiciousItemMapper suspiciousItemMapper;
    @Autowired
    private TbWmsMaterialDeliveryLineMapper mapper;
    @Autowired
    private TbWmsLocationMapper tbWmsLocationMapper;
    @Autowired
    private TbWmsMaterialReceiptNotExistMapper tbWmsMaterialReceiptNotExistMapper;
    @Autowired
    private TbWmsMaterialReceiptLineMapper tbWmsMaterialReceiptLineMapper;
    @Autowired
    private TbWmsMaterialDeliveryMapper tbWmsMaterialDeliveryMapper;
    @Autowired
    private CustomerConsigneeMapper customerConsigneeMapper;
    @Autowired
    private TbWmsMaterialReceiptMapper tbWmsMaterialReceiptMapper;
    @Autowired
    private IBmsAllGeneralSeqTabService tBmsAllGeneralSeqTabService;
    @Autowired
    private SkuMapper skuMapper;
    @Autowired
    private SpuMapper spuMapper;

    @Autowired
    private WarehouseMapper tWhWarehouseMapper;
    @Autowired
    private CustomerMapper customerMapper;
    @Autowired
    private SupplierMapper supplierMapper;
    @Autowired
    private OperationLogMapper operationLogMapper;
    @Autowired
    private TbWmsMaterialInLocationMapper tbWmsMaterialInLocationMapper;
    @Autowired
    private TWhWarehouseCustomerMaterialMapper tWhWarehouseCustomerMaterialMapper;
    @Autowired
    private WarehouseMapper warehouseMapper;
    @Autowired
    private TbUserWarehouseManagerMapMapper tbUserWarehouseManagerMapMapper;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private ITbWmsMaterialDeliveryService iTbWmsMaterialDeliveryvice;

    @Autowired
    private IConfigService sysConfigService;
    /**
     * 新增
     * @param params
     * @return
     */
    @Transactional(readOnly = false)
    @Override
    public String insert(TbWmsMaterialDeliveryLineSaveParam params) {
        UserVo sysUser = tokenService.getLoginUser(ServletUtils.getRequest()).getUser();
        TbWmsMaterialDeliveryLine entity = new TbWmsMaterialDeliveryLine();
        BeanUtils.copyProperties(params, entity);
        entity.setId(idWorker.nextId() + "").preInsert(sysUser.getId());
        this.mapper.insert(entity);
        return entity.getId();
    }

    @Override
    public TbWmsMaterialDeliveryLineVo removeSpecialChar(TbWmsMaterialDeliveryLineVo input){
        Pattern p =null;
        Matcher m = null;;
        String rt = "";

        if(!StringUtils.isNull(input.getCustomerNo())) {
            p = Pattern.compile("\\s*|\t|\r|\n");
            m = p.matcher(input.getCustomerNo());
            rt = m.replaceAll("");
            input.setCustomerNo(rt);
        }
        if(!StringUtils.isNull(input.getCustomerName())) {
            p = Pattern.compile("\\s*|\t|\r|\n");
            m = p.matcher(input.getCustomerName());
            rt = m.replaceAll("");
            input.setCustomerName(rt);
        }

        if(!StringUtils.isNull(input.getSupplierName())) {
            p = Pattern.compile("\\s*|\t|\r|\n");
            m = p.matcher(input.getSupplierName());
            rt = m.replaceAll("");
            input.setSupplierName(rt);
        }

        if(!StringUtils.isNull(input.getSupplierNo())) {
            p = Pattern.compile("\\s*|\t|\r|\n");
            m = p.matcher(input.getSupplierNo());
            rt = m.replaceAll("");
            input.setSupplierNo(rt);
        }

        if(!StringUtils.isNull(input.getCloseReason())) {
            p = Pattern.compile("\\s*|\t|\r|\n");
            m = p.matcher(input.getCloseReason());
            rt = m.replaceAll("");
            input.setCloseReason(rt);
        }

        if(!StringUtils.isNull(input.getDeliveryWarehouseAreaCode())) {
            p = Pattern.compile("\\s*|\t|\r|\n");
            m = p.matcher(input.getDeliveryWarehouseAreaCode());
            rt = m.replaceAll("");
            input.setDeliveryWarehouseAreaCode(rt);
        }
        if(!StringUtils.isNull(input.getDeliveryWarehouseAreaName())){
            p = Pattern.compile("\\s*|\t|\r|\n");
            m = p.matcher(input.getDeliveryWarehouseAreaName());
            rt = m.replaceAll("");
            input.setDeliveryWarehouseAreaName(rt);
        }
        if(!StringUtils.isNull(input.getDeliveryWarehouseCode())){
            p = Pattern.compile("\\s*|\t|\r|\n");
            m = p.matcher(input.getDeliveryWarehouseCode());
            rt = m.replaceAll("");
            input.setDeliveryWarehouseCode(rt);
        }
        if(!StringUtils.isNull(input.getDeliveryWarehouseName())){
            p = Pattern.compile("\\s*|\t|\r|\n");
            m = p.matcher(input.getDeliveryWarehouseName());
            rt = m.replaceAll("");
            input.setDeliveryWarehouseName(rt);
        }
        if(!StringUtils.isNull(input.getExcelQuantity())){
            p = Pattern.compile("\\s*|\t|\r|\n");
            m = p.matcher(input.getExcelQuantity());
            rt = m.replaceAll("");
            if(StringUtils.isDouble(rt)){
                input.setExcelQuantity(rt);
            }
        }
        if(!StringUtils.isNull(input.getMaterialNo())){
            p = Pattern.compile("\\s*|\t|\r|\n");
            m = p.matcher(input.getMaterialNo());
            rt = m.replaceAll("");
            input.setMaterialNo(rt);
        }
        if(!StringUtils.isNull(input.getMaterialName())){
            p = Pattern.compile("\\s*|\t|\r|\n");
            m = p.matcher(input.getMaterialName());
            rt = m.replaceAll("");
            input.setMaterialName(rt);
        }
        if(!StringUtils.isNull(input.getUnloadDockName())){
            p = Pattern.compile("\\s*|\t|\r|\n");
            m = p.matcher(input.getUnloadDockName());
            rt = m.replaceAll("");
            input.setUnloadDockName(rt);
        }
        if(!StringUtils.isNull(input.getUnloadDockCode())){
            p = Pattern.compile("\\s*|\t|\r|\n");
            m = p.matcher(input.getUnloadDockCode());
            rt = m.replaceAll("");
            input.setUnloadDockCode(rt);
        }
        if(!StringUtils.isNull(input.getDistributeRouteCode())){
            p = Pattern.compile("\\s*|\t|\r|\n");
            m = p.matcher(input.getDistributeRouteCode());
            rt = m.replaceAll("");
            input.setDistributeRouteCode(rt);
        }
        if(!StringUtils.isNull(input.getReceStatus())){
            p = Pattern.compile("\\s*|\t|\r|\n");
            m = p.matcher(input.getReceStatus());
            rt = m.replaceAll("");
            input.setReceStatus(rt);
        }
        if(!StringUtils.isNull(input.getDeliveryStatus())){
            p = Pattern.compile("\\s*|\t|\r|\n");
            m = p.matcher(input.getDeliveryStatus());
            rt = m.replaceAll("");
            input.setDeliveryStatus(rt);
        }
        if(!StringUtils.isNull(input.getDiffShipReason())){
            p = Pattern.compile("\\s*|\t|\r|\n");
            m = p.matcher(input.getDiffShipReason());
            rt = m.replaceAll("");
            input.setDiffShipReason(rt);
        }

        return input;
    }


    @Transactional(readOnly = false)
    public TbWmsMaterialDelivery addNewOrder
            (TbWmsMaterialDeliveryLineVo tbWmsMaterialDeliveryLineVo,UserVo user, int line) {

        TbWmsMaterialDelivery tbWmsMaterialDelivery = new TbWmsMaterialDelivery();
        String importError = "";
        String errorFlag = "N";

        String orderNo = tBmsAllGeneralSeqTabService.generateNo("materialDelivery");

        List<TbWmsMaterialDeliveryLine> tbWmsMaterialDeliveryLines =
                this.mapper.findBySupplierNoAndMaterialNoAndOrderNo(tbWmsMaterialDeliveryLineVo.getSupplierNo(),tbWmsMaterialDeliveryLineVo.getMaterialNo(),tbWmsMaterialDeliveryLineVo.getCaseNo());

        if(tbWmsMaterialDeliveryLines!=null&&tbWmsMaterialDeliveryLines.size()>0){

            OperationLog operationLog =new OperationLog();
            operationLog.setOperationType(ErrorType.ORDERIMPORT.getStatusName());
            operationLog.setErrorMsg("订单已经输入，不可重复输入 ");
            operationLog.setMethod("101");
            operationLog.setLocation(tbWmsMaterialDeliveryLineVo.getOrderNo());
            operationLog.setId(idWorker.nextId() + "").preInsert(user != null ? user.getId() : ApiConstants.DEFAULT_USER_ID);
            if (user != null) {
                operationLog.setOperatorName(user.getUserName() + "(" + user.getNickName() + ")");
            }
            operationLogMapper.insert(operationLog);
            if(!StringUtils.isNull(importError)){
                importError =
                        importError.concat(operationLog.getLocation().concat(operationLog.getErrorMsg()));
                // salesOrderItem.setImportErrorMesg(errorMsg);
                tbWmsMaterialDelivery.setErrorFlag("Y");
            }else{
                // salesOrderItem.setImportErrorMesg(operationLog.getLocation().concat(operationLog.getErrorMsg()));
                importError = "订单已经输入，不可重复输入 ";
                tbWmsMaterialDelivery.setErrorFlag("Y");
                tbWmsMaterialDelivery.setImportErrorMesg(importError);
            }
            return null;
        }

        tbWmsMaterialDelivery.setSiteCode(user.getSite())
                .setStatus(WmsInStatusEnum.created.getValue());
        if (!StringUtils.isNull(tbWmsMaterialDeliveryLineVo.getSupplierNo())) {

            SupplierVo supplierVo = supplierMapper.findByCode(tbWmsMaterialDeliveryLineVo.getSupplierNo());


            if (supplierVo != null) {

            } else {
                Supplier supplier =new Supplier();
                supplier.setSite(user.getSite());
                supplier.setSupplierDesc(tbWmsMaterialDeliveryLineVo.getSupplierName());
                supplier.setSupplierType("parts");
                supplier.setSupplierFullName(tbWmsMaterialDeliveryLineVo.getSupplierName());
                supplier.setSupplierName(tbWmsMaterialDeliveryLineVo.getSupplierName());
                supplier.setSupplierCode(tbWmsMaterialDeliveryLineVo.getSupplierNo());
                supplier.setId(idWorker.nextId() + "").preInsert(user.getId());
                this.supplierMapper.insert(supplier);
                OperationLog operationLog = new OperationLog();
                operationLog.setOperationType(ErrorType.ORDERIMPORT.getStatusName());
                operationLog.setErrorMsg(tbWmsMaterialDeliveryLineVo.getCaseNo() + "供应商基础数据通过拉动单新建");
                operationLog.setMethod("601");
                operationLog.setLocation("新建供应商:".concat(tbWmsMaterialDeliveryLineVo.getSupplierName()));
                operationLog.setId(idWorker.nextId() + "").preInsert(user != null ? user.getId() : ApiConstants.DEFAULT_USER_ID);
                if (user != null) {
                    operationLog.setOperatorName(user.getUserName() + "(" + user.getNickName() + ")");
                }
                operationLogMapper.insert(operationLog);

                importError = "供应商没有查到";
                errorFlag = "Y";
            }
        } else {
            OperationLog operationLog = new OperationLog();
            operationLog.setOperationType(ErrorType.ORDERIMPORT.getStatusName());
            operationLog.setErrorMsg(tbWmsMaterialDeliveryLineVo.getCaseNo() + "供应商基础数据没有提供");
            operationLog.setMethod("601");
            operationLog.setLocation("子订单号:".concat(tbWmsMaterialDeliveryLineVo.getId()));

            operationLog.setId(idWorker.nextId() + "").preInsert(user != null ? user.getId() : ApiConstants.DEFAULT_USER_ID);
            if (user != null) {
                operationLog.setOperatorName(user.getUserName() + "(" + user.getNickName() + ")");
            }
            operationLogMapper.insert(operationLog);
            importError = "店铺数据原始订单未提供";
            errorFlag = "Y";
        }
        // String orderNo = this.generalSeqService.generateSeq("oms_sales_order");


        tbWmsMaterialDelivery.setCustomerNo(tbWmsMaterialDeliveryLineVo.getCustomerNo());
        tbWmsMaterialDelivery.setCustomerName(tbWmsMaterialDeliveryLineVo.getCustomerName());
        tbWmsMaterialDelivery.setConsigneeAddress(tbWmsMaterialDeliveryLineVo.getUnloadDockName());
        tbWmsMaterialDelivery.setOrderType(SalesOrderTypeEnum.ByCustomerExcel.getValue());
        tbWmsMaterialDelivery.setConsignee(tbWmsMaterialDeliveryLineVo.getUnloadDockCode());
        tbWmsMaterialDelivery.setConsigneeName(tbWmsMaterialDeliveryLineVo.getUnloadDockName());
        tbWmsMaterialDelivery.setErrorFlag(errorFlag);
        tbWmsMaterialDelivery.setId(idWorker.nextId() + "").preInsert(user != null ? user.getId() : ApiConstants.DEFAULT_USER_ID);
        tbWmsMaterialDelivery.setOrderNo(orderNo);
        this.tbWmsMaterialDeliveryMapper.insert(tbWmsMaterialDelivery);


        return tbWmsMaterialDelivery;
    }
    /**
     * 导入
     * @param data
     * @return
     */
    @Transactional(readOnly = false)
    @Override
    public TbWmsMaterialDelivery importData( TbWmsMaterialDeliveryLineVo data, String needOrderYn, UserVo user, int itemNo, int line, TbWmsMaterialDelivery tbWmsMaterialDelivery) {
        data = this.removeSpecialChar(data);


        //   if (needOrderYn.equals("No")) {
        //       TbWmsMaterialDeliveryLine tbWmsMaterialDeliveryLine = this.addNewItem(tbWmsMaterialDelivery, data, user, itemNo, line);
        //       return tbWmsMaterialDelivery;
        //   } else {
        TbWmsMaterialDelivery tbWmsMaterialDeliverynext = this.addNewOrder(data, user,line);
        if(tbWmsMaterialDeliverynext!=null){
            TbWmsMaterialDeliveryLine tbWmsMaterialDeliveryLine = this.addNewItem(tbWmsMaterialDeliverynext, data, user, itemNo, line);
        //    this.iTbWmsMaterialDeliveryvice.findByDateAndShipperAndUpdateCalendar(tbWmsMaterialDeliverynext,tbWmsMaterialDeliverynext.getCustomerNo(),user);
            return tbWmsMaterialDeliverynext;
        }else{
            return null;
        }

        //  }
    }
    /**
     * 删除
     * @param id
     * @return
     */
    @Transactional(readOnly = false)
    @Override
    public Integer delete(String id) {
        return this.mapper.deleteById(id);
    }

    /**
     * 批量删除
     * @param idList
     */
    @Transactional(readOnly = false)
    @Override
    public Integer batchDelete(List<String> idList) {
        if (ListUtils.isNotEmpty(idList)) {
            return this.mapper.deleteBatchIds(idList);
        } else {
            return 0;
        }
    }

    /**
     * 出库确认
     * @param params
     * @return
     */
    @Transactional(readOnly = false)
    @Override
    public Integer outbound(TbWmsMaterialDeliveryLineSaveParam params) {
        List<String> rfids = params.getRfidCodes();
        List<TbWmsMaterialDeliveryLineSaveParam> locationObjs = new ArrayList<TbWmsMaterialDeliveryLineSaveParam>();
        List<String> locations = new ArrayList<String>();
        TbWmsLocation tbWmsLot = null;
        TbWmsMaterialDeliveryLineSaveParam temParam= new TbWmsMaterialDeliveryLineSaveParam();
        String ids= "";
        for(int i= 0; i <rfids.size();i++){
            List<TbWmsMaterialDeliveryLine> entityFromDbs = this.mapper.findByRfid((String)rfids.get(i));
            if(i==0){
                ids =(String)rfids.get(i);
            }else if(ids ==""){
                ids= (String)rfids.get(i);
            }else {
                ids= ids.concat(",").concat((String)rfids.get(i));
            }
            UserVo sysUser = tokenService.getLoginUser(ServletUtils.getRequest()).getUser();
            for(int j=0;j<entityFromDbs.size();j++){
                TbWmsMaterialDeliveryLine entityFromDb = (TbWmsMaterialDeliveryLine)entityFromDbs.get(j);

                entityFromDb.setStatus(WmsOutStatusEnum.outed.getValue());
                entityFromDb.preUpdate(sysUser.getId());
                this.mapper.updateById(entityFromDb);
                if(!locations.contains(entityFromDb.getLocationNo())){
                    locations.add(entityFromDb.getLocationNo());
                    temParam.setLocationNo(entityFromDb.getLocationNo());
                    temParam.setId(ids);
                    ids ="";
                    locationObjs.add(temParam);
                    tbWmsLot =this.tbWmsLocationMapper.findByLocationNo(entityFromDb.getLocationNo());
                }

                if(entityFromDb.getWeight()!=null){
                    Double currentlocationload = tbWmsLot.getCurrentLoad();
                    if(currentlocationload!=null){
                        Double totload = NumberUtils.add(currentlocationload,entityFromDb.getWeight());
                        tbWmsLot.setCurrentLoad(totload);
                        tbWmsLot.preUpdate(sysUser.getId());
                        this.tbWmsLocationMapper.updateById(tbWmsLot);
                    }

                }
            }

            //  double needoutNumber = entityFromDb.getQuantity().doubleValue();
            // List <TbWmsMaterialInLocation> tbWmsMaterialInLocations  =
            //       this.tbWmsMaterialInLocationMapper.findByMaterialNo(entityFromDb.getMaterialNo());
            List<TbWmsMaterialInLocation>  tbWmsMaterialInLocations  =
                    this.tbWmsMaterialInLocationMapper.findByrfid((String)rfids.get(i));
            if(tbWmsMaterialInLocations!=null){
                for(int j=0;j<tbWmsMaterialInLocations.size();j++){
                    TbWmsMaterialInLocation tbWmsMaterialInLocation =(TbWmsMaterialInLocation)tbWmsMaterialInLocations.get(j);
                    this.tbWmsMaterialInLocationMapper.deleteById(tbWmsMaterialInLocation.getId());
                }

            }

         /*   for(int j=0;j<tbWmsMaterialInLocations.size();j++){
                TbWmsMaterialInLocation tbWmsMaterialInLocation = (TbWmsMaterialInLocation)tbWmsMaterialInLocations.get(j);
                if(tbWmsMaterialInLocation.getQuantity().doubleValue()<=needoutNumber)
                {
                    this.tbWmsMaterialInLocationMapper.deleteById(tbWmsMaterialInLocation.getId());
                    needoutNumber = needoutNumber-tbWmsMaterialInLocation.getQuantity().doubleValue();
                    if(needoutNumber<=0){
                        break;
                    }
                }else{
                    Double nownum = NumberUtils.sub(tbWmsMaterialInLocation.getQuantity().doubleValue(),needoutNumber);
                    tbWmsMaterialInLocation.setQuantity(new BigDecimal(nownum));
                    tbWmsMaterialInLocation.preUpdate(sysUser.getId());
                    this.tbWmsMaterialInLocationMapper.updateById(tbWmsMaterialInLocation);

                    break;
                }
            }*/

        }
        for(int j=0; j<locationObjs.size();j++){
            TbWmsMaterialDeliveryLineSaveParam tbWmsMaterialDeliveryLineSaveParam
                    =(TbWmsMaterialDeliveryLineSaveParam)locationObjs.get(j);
            this.autoWarehouseFetch(tbWmsMaterialDeliveryLineSaveParam.getLocationNo(),tbWmsMaterialDeliveryLineSaveParam.getId());
        }

        return 0;
    }

    /**
     * 取货处理
     * @param locationNo
     * @return
     */
    @Transactional(readOnly = false)
    @Override
    public String autoWarehouseFetch(String locationNo,String rfids){
        JSONObject params = new JSONObject();
        JSONObject data = new JSONObject();
        data.put("Location",locationNo);
        data.put("Url", "http://192.168.1.15:39527/api/StorageFetchCallback");
        data.put("Id",rfids);
        params.put("Status", 1);
        params.put("ErrorCode", 200);
        params.put("ErrorMsg", "成功");
        params.put("Data", data);
        String SignatureUrl = sysConfigService.findByConfigKey("Fetch.url");
        String resp = HttpClientUtils.ajaxPostJson(SignatureUrl, JSONObject.toJSONString(params));
      /*   JSONObject respObj = JSONObject.parseObject(resp);
        if (respObj.getInteger("ErrorCode") == 200) {
            log.info("调用取料接口成功");
        } else {
            log.error("调用取料接口失败，错误原因：{}", respObj.getString("ErrorMsg"));
        }
     */
        return "success";
    }
    /**
     * 修改
     * @param params
     * @return
     */
    @Transactional(readOnly = false)
    @Override
    public Integer update(TbWmsMaterialDeliveryLineSaveParam params) {
        TbWmsMaterialDeliveryLine entityFromDb = this.mapper.selectById(params.getId());
        if (entityFromDb == null) {
            throw new ParamException("id=" + params.getId());
        }
        UserVo sysUser = tokenService.getLoginUser(ServletUtils.getRequest()).getUser();
        BeanUtils.copyProperties(params, entityFromDb);
        entityFromDb.preUpdate(sysUser.getId());
        return this.mapper.updateById(entityFromDb);
    }

    /**
     * 详情
     * @param id
     * @return
     */
    @Override
    public TbWmsMaterialDeliveryLineVo findById(String id) {
        return this.mapper.findById(id);
    }

    /**
     * 列表
     * @param params
     * @return
     */
    @Override
    public List<TbWmsMaterialDeliveryLineVo> findAll(TbWmsMaterialDeliveryLineSearchParam params) {
     //   zheli jia cangku 管理员逻辑
        UserVo sysUser = tokenService.getLoginUser(ServletUtils.getRequest()).getUser();
        List<String> warehouseNos = new ArrayList<String>();
        warehouseNos = this.tbUserWarehouseManagerMapMapper.findAllWarehouseIds(sysUser.getId());
        params.setWarehouseNoList(warehouseNos);
        return this.mapper.findAll(params);
    }
    @Override
    @Transactional(readOnly = false)
    public List<TbWmsMaterialDeliveryLine> findAllOrderByMaterial(TbWmsMaterialDeliveryLineSearchParam params) {
        //这里需要把货位更新上去 把入库单号也更新上去 要实现先进先出等
        List<TbWmsMaterialDeliveryLine> needOuts =  this.mapper.findAllOrderByMaterial(params);
        List<TbWmsMaterialDeliveryLine> rtneedOuts =new ArrayList<TbWmsMaterialDeliveryLine>();
        for(int i = 0; i<needOuts.size();i++){
            TbWmsMaterialDeliveryLine tbWmsMaterialDeliveryLine = (TbWmsMaterialDeliveryLine)needOuts.get(i);
            Double addedQty = 0.0;
            String receptIds = " ";
            String locationNos = " ";
            if(tbWmsMaterialDeliveryLine.getInAndOutType()!=null){
                if(tbWmsMaterialDeliveryLine.getInAndOutType().equals("先进先出")){
                    List<TbWmsMaterialInLocationVo> tbWmsMaterialInLocationVos =
                            this.tbWmsMaterialInLocationMapper.findMaterialByFifo(tbWmsMaterialDeliveryLine.getMaterialNo());
                    for(int j=0; j <tbWmsMaterialInLocationVos.size();j++){
                        TbWmsMaterialInLocationVo tbWmsMaterialInLocationVo = (TbWmsMaterialInLocationVo)tbWmsMaterialInLocationVos.get(j);
                        addedQty = NumberUtils.add(addedQty,tbWmsMaterialInLocationVo.getQuantity());
                        receptIds = receptIds.concat(tbWmsMaterialInLocationVo.getReceivedLineId()).concat(";");
                        locationNos = locationNos.concat(tbWmsMaterialInLocationVo.getLocationNo()).concat(";");
                        if(addedQty>=tbWmsMaterialDeliveryLine.getQuantity()){
                            break;
                        }
                    }
                }else{
                    List<TbWmsMaterialInLocation> tbWmsMaterialInLocationVos =
                            this.tbWmsMaterialInLocationMapper.findByMaterialNo(tbWmsMaterialDeliveryLine.getMaterialNo());
                    for(int j=0; j <tbWmsMaterialInLocationVos.size();j++){
                        TbWmsMaterialInLocation tbWmsMaterialInLocation = (TbWmsMaterialInLocation)tbWmsMaterialInLocationVos.get(j);
                        addedQty = NumberUtils.add(addedQty,tbWmsMaterialInLocation.getQuantity());
                        receptIds = receptIds.concat(tbWmsMaterialInLocation.getReceivedLineId()).concat(";");
                        locationNos = locationNos.concat(tbWmsMaterialInLocation.getLocationNo()).concat(";");
                        if(addedQty>=tbWmsMaterialDeliveryLine.getQuantity()){
                            break;
                        }
                    }
                }
            }else{
                List<TbWmsMaterialInLocation> tbWmsMaterialInLocationVos =
                        this.tbWmsMaterialInLocationMapper.findByMaterialNo(tbWmsMaterialDeliveryLine.getMaterialNo());
                for(int j=0; j <tbWmsMaterialInLocationVos.size();j++){
                    TbWmsMaterialInLocation tbWmsMaterialInLocation = (TbWmsMaterialInLocation)tbWmsMaterialInLocationVos.get(j);
                    addedQty = NumberUtils.add(addedQty,tbWmsMaterialInLocation.getQuantity());
                    receptIds = receptIds.concat(tbWmsMaterialInLocation.getReceivedLineId()).concat(";");
                    locationNos = locationNos.concat(tbWmsMaterialInLocation.getLocationNo()).concat(";");
                    if(addedQty>=tbWmsMaterialDeliveryLine.getQuantity()){
                        break;
                    }
                }
            }
            tbWmsMaterialDeliveryLine.setLocationNo(locationNos);
            tbWmsMaterialDeliveryLine.setReceivedLineId(receptIds);
            tbWmsMaterialDeliveryLine.preUpdate(ApiConstants.DEFAULT_USER_ID);
            this.mapper.updateById(tbWmsMaterialDeliveryLine);
            rtneedOuts.add(tbWmsMaterialDeliveryLine);
        }
        return rtneedOuts;
    }
    @Transactional(readOnly = false)
    @Override
    public String confirm(String id){
        TbWmsMaterialDeliveryLine item = this.mapper.selectById(id);
        UserVo user = tokenService.getLoginUser(ServletUtils.getRequest()).getUser();

        item.setStatus(WmsOutStatusEnum.confirmed.getValue());
        item.preUpdate(user.getId());
        this.mapper.updateById(item);

        return item.getId();
    }
    @Transactional(readOnly = false)
    @Override
    public String moveToSuspicious(TbWmsMaterialDeliveryLineSaveParam param){
        TbWmsMaterialDeliveryLine item = this.mapper.selectById(param.getId());
        UserVo user = tokenService.getLoginUser(ServletUtils.getRequest()).getUser();

        item.setStatus(WmsOutStatusEnum.suspicious.getValue());
        item.preUpdate(user.getId());
        this.mapper.updateById(item);
        SuspiciousItem suspiciousItem = new SuspiciousItem();
        suspiciousItem.setDesc(param.getDesc());
        suspiciousItem.setSuspiciousType("outWarehouse");
        suspiciousItem.setOrderNo(item.getId());
        suspiciousItem.setId(idWorker.nextId() + "").preInsert(user.getId());
        this.suspiciousItemMapper.insert(suspiciousItem);
        return suspiciousItem.getId();
    }
    /**
     * 列表-分页
     * @param params
     * @param current
     * @param pageSize
     * @return
     */
    @Override
    public IPage<TbWmsMaterialDeliveryLineVo> findAll(TbWmsMaterialDeliveryLineSearchParam params, Integer current, Integer pageSize) {
        UserVo sysUser = tokenService.getLoginUser(ServletUtils.getRequest()).getUser();
        List<String> warehouseNos = new ArrayList<String>();
        warehouseNos = this.tbUserWarehouseManagerMapMapper.findAllWarehouseIds(sysUser.getId());
        params.setWarehouseNoList(warehouseNos);
        return this.mapper.findAll(new Page<>(current, pageSize), params);
    }

    /**
     * 列表-分页
     * @param params
     * @param current
     * @param pageSize
     * @return
     */
    @Override
    public IPage<TbWmsMaterialDeliveryLineptVo> findAll1(TbWmsMaterialDeliveryLineSearchParam params, Integer current, Integer pageSize) {
        UserVo sysUser = tokenService.getLoginUser(ServletUtils.getRequest()).getUser();
        List<String> warehouseNos = new ArrayList<String>();
        warehouseNos = this.tbUserWarehouseManagerMapMapper.findAllWarehouseIds(sysUser.getId());
        params.setWarehouseNoList(warehouseNos);
        return this.mapper.findAll1(new Page<>(current, pageSize), params);
    }

    @Transactional(readOnly = false)
    @Override
    public String importData1(MultipartFile file) {
        List<TbWmsMaterialDeliveryLineptVo> dataList = null;
        UserVo user = tokenService.getLoginUser(ServletUtils.getRequest()).getUser();
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();

        int successNum = 0;
        int failureNum = 0;
        int logNum = 0;
        try {
            ExcelImport excelImport = new ExcelImport(file, 1, 0);
            dataList = excelImport.getDataList(TbWmsMaterialDeliveryLineptVo.class);
        } catch (Exception e) {
            log.error("获取数据信息失败!");
            throw new ExcelException("获取数据信息失败!");
        }
        if (ListUtils.isEmpty(dataList)) {
            throw new ExcelException("导入数据不能为空！");
        }

        if(dataList==null||dataList.size()==0){
            //return "没有读取到数据";
            log.error("没有读取到数据!");
        }

        String custOrderNo ="";
        SalesOrder newSalesOrder = null;
        int itemNo = 0;
        int line = 0;
        TbWmsMaterialDeliveryLine entity = new TbWmsMaterialDeliveryLine();
        TbWmsMaterialReceiptLineSearchParam tbWmsMaterialReceiptLineSearchParam= new TbWmsMaterialReceiptLineSearchParam();
        for (TbWmsMaterialDeliveryLineptVo data : dataList) {
            tbWmsMaterialReceiptLineSearchParam.setVinNo(data.getVinNo());
            tbWmsMaterialReceiptLineSearchParam.setStatus("created");
            //tbWmsMaterialReceiptLineSearchParam.setCarrierNo("isNotNull");
            List<TbWmsMaterialReceiptLineVo> tbWmsMaterialReceiptLineVo = tbWmsMaterialReceiptLineMapper.findByVinNo(tbWmsMaterialReceiptLineSearchParam);



            if(tbWmsMaterialReceiptLineVo.size()<=0){
                //空入空出
                TbWmsMaterialReceiptNotExist tbWmsMaterialReceiptNotExist = new TbWmsMaterialReceiptNotExist();
                BeanUtils.copyProperties(data, tbWmsMaterialReceiptNotExist);
                UserVo sysUser = tokenService.getLoginUser(ServletUtils.getRequest()).getUser();

                tbWmsMaterialReceiptNotExist.setOrderNo("1");
                tbWmsMaterialReceiptNotExist.setId(idWorker.nextId() + "").preInsert(sysUser.getId());
                tbWmsMaterialReceiptNotExistMapper.insert(tbWmsMaterialReceiptNotExist);
                line++;
            }else{
                successNum++;

                List<TbWmsMaterialInLocation> tbWmsMaterialInLocationList = this.tbWmsMaterialInLocationMapper.findByReciptLineId(tbWmsMaterialReceiptLineVo.get(0).getId());

                //如果库存处于外借或者维修状态 无法出库。
                if(!tbWmsMaterialInLocationList.get(0).getStatus().equals("inposition")){
                    itemNo++;
                    continue;
                }

                TWhWarehouseCustomerMaterial tWhWarehouseCustomerMaterial = this.tWhWarehouseCustomerMaterialMapper.findByMaterialNoAndCustomerNo(data.getMaterialNo(),data.getCustomerNo());
                if(tWhWarehouseCustomerMaterial==null){
                    tWhWarehouseCustomerMaterial = new TWhWarehouseCustomerMaterial();
                    BeanUtils.copyProperties(data, tWhWarehouseCustomerMaterial);
                    tWhWarehouseCustomerMaterial.setMaterialNo(data.getMaterialNo());
                    tWhWarehouseCustomerMaterial.setVehicleModel(data.getMaterialNo());
                    tWhWarehouseCustomerMaterial.setMeasUnitNo("辆");
                    tWhWarehouseCustomerMaterial.setId(idWorker.nextId() + "").preInsert(user.getId());
                    this.tWhWarehouseCustomerMaterialMapper.insert(tWhWarehouseCustomerMaterial);
                }
                Warehouse warehouse  = warehouseMapper.findByCode(data.getDeliveryWarehouseCode());
                String warehouseId = null;
                if(StringUtils.isNull(warehouse)){
                    warehouse = new Warehouse();
                    warehouse.setWarehouserCode(data.getDeliveryWarehouseCode());
                    warehouse.setWarehouserName(data.getDeliveryWarehouseCode());
                    warehouse.setWarehouseType("center");
                    warehouse.setId(idWorker.nextId() + "").preInsert(user.getId());
                    warehouseMapper.insert(warehouse);
                    warehouseId = warehouse.getId();
                }else{
                    warehouseId = warehouse.getId();
                }
                CustomerConsignee customerConsignee = this.customerConsigneeMapper.findByCode(data.getConsignee());
                if(customerConsignee==null){
                    customerConsignee = new CustomerConsignee();
                    customerConsignee.setCustomerNo(data.getCustomerNo());
                    customerConsignee.setCcccode(data.getConsignee());
                    customerConsignee.setWarehouseCode(warehouseId);
                    customerConsignee.setConsigneeName(data.getConsigneeName());
                    customerConsignee.setConsigneeAddress(data.getConsigneeAddress());
                    customerConsignee.setIsValid("1");
                    customerConsignee.setId(idWorker.nextId() + "").preInsert(user.getId());
                    this.customerConsigneeMapper.insert(customerConsignee);
                }
                TbWmsMaterialDelivery tbWmsMaterialDelivery = new TbWmsMaterialDelivery();
                /*BeanUtils.copyProperties(params, entity);*/
                // 新增运单主表信息
                if(StringUtils.isNull(tbWmsMaterialDelivery.getOrderNo())){
                    String orderNo = tBmsAllGeneralSeqTabService.generateNo("materialDelivery");
                    tbWmsMaterialDelivery.setOrderNo("R".concat(orderNo));
                }
                tbWmsMaterialDelivery.setCustomerNo("1000");
                tbWmsMaterialDelivery.setConsignee(customerConsignee==null?customerConsignee.getId():data.getConsignee());
                tbWmsMaterialDelivery.setCustomerName(customerConsignee==null?customerConsignee.getId():data.getCustomerName());
                tbWmsMaterialDelivery.setWarehouseCode(warehouseId);
                tbWmsMaterialDelivery.setStatus("created");
                tbWmsMaterialDelivery.setId(idWorker.nextId() + "").preInsert(user.getId());

                tbWmsMaterialDeliveryMapper.insert(tbWmsMaterialDelivery);



                BeanUtils.copyProperties(data, entity);
                entity.setDeliveryWarehouseCode(warehouseId);
                //entity.setConsignee(customerConsignee.getId());
                entity.setConsigneeAddress(customerConsignee.getConsigneeAddress());
                /*entity.setConsigneeName(customerConsignee.getConsigneeName());
                entity.setConsigneePhoneNo(customerConsignee.getLinkManMobile());*/
                entity.setStatus("created");
                entity.setOrderNo(tbWmsMaterialDelivery.getOrderNo());
                entity.setVehicleLoadType(tWhWarehouseCustomerMaterial.getMaterialType());
                entity.setDeliveryId(tbWmsMaterialDelivery.getId());
                entity.setFreightQuantity(new BigDecimal(data.getQuantity()));
                entity.setDeliveryQuantity(new BigDecimal(data.getQuantity()));
                entity.setSite(user.getOrgId());
                entity.setReceivedLineId(tbWmsMaterialReceiptLineVo.get(0).getId());
                entity.setId(idWorker.nextId() + "").preInsert(user.getId());
                entity.setDeliveryType("vehicle");
                entity.setShipByPackOrqty("qty");
                entity.setWeight(Double.valueOf("1"));
                entity.setPickUpWarehouseNo(warehouseId);
                entity.setLocationNo(tbWmsMaterialReceiptLineVo.get(0).getLocationNo());
                entity.setMaterialName(tbWmsMaterialReceiptLineVo.get(0).getMaterialName());
                entity.setRequestDeliveryTime(data.getRequestDeliveryTime());
                if(tbWmsMaterialInLocationList.size()>0){
                    entity.setMaterialVehicleInLocationId(tbWmsMaterialInLocationList.get(0).getId());
                }

                this.mapper.insert(entity);

                /*tbWmsMaterialInLocationList.get(0).setIsValid("0");
                tbWmsMaterialInLocationList.get(0).setStatus("outPlaned");
                tWhWarehouseCustomerMaterialMapper.updateById(tbWmsMaterialInLocationList.get(0))*/

                tbWmsMaterialReceiptLineVo.get(0).setStatus(WmsInStatusEnum.outPlaned.getValue());
                tbWmsMaterialReceiptLineVo.get(0).setUpdateBy(user.getId());
                TbWmsMaterialReceiptLine line1 = new TbWmsMaterialReceiptLine();
                BeanUtils.copyProperties(tbWmsMaterialReceiptLineVo.get(0), line1);
                tbWmsMaterialReceiptLineMapper.updateById(line1);

                TbWmsMaterialReceipt receipt = this.tbWmsMaterialReceiptMapper.selectById(line1.getReceiptId());
                receipt.setStatus(WmsInStatusEnum.outPlaned.getValue());
                receipt.preUpdate(user.getId());
                this.tbWmsMaterialReceiptMapper.updateById(receipt);
            }
        }


        successMsg.insert(0, "恭喜您，数据已导入成功！共 " + successNum + " 条，根据VIN号未查询到入库信息共 "+line+" 条，库存处于外借或者维修的共 "+itemNo+" 条。");


        return successMsg.toString();
    }

    @Transactional(readOnly = false)
    public TbWmsMaterialDeliveryLine addNewItem(TbWmsMaterialDelivery tbWmsMaterialDelivery, TbWmsMaterialDeliveryLineVo data,UserVo user,int itemNo,int line){

        TbWmsMaterialDeliveryLine tbWmsMaterialDeliveryLine = new TbWmsMaterialDeliveryLine();
        tbWmsMaterialDeliveryLine.setErrorFlag(tbWmsMaterialDelivery.getErrorFlag());
        if(!StringUtils.isNull(tbWmsMaterialDelivery.getErrorCode())){
            tbWmsMaterialDeliveryLine.setErrorCode(tbWmsMaterialDelivery.getErrorCode());
            if(tbWmsMaterialDelivery.getErrorCode().equals("101")){
                tbWmsMaterialDeliveryLine.setErrorFlag("Y");
            }
        }
        String errorMsg = tbWmsMaterialDelivery.getImportErrorMesg();
        String itemErrorMsg = "明细保存：";
        BeanUtils.copyProperties(data, tbWmsMaterialDeliveryLine);
        List<TbWmsMaterialDeliveryLine> tbWmsMaterialDeliveryLines =
                this.mapper.findBySupplierNoAndMaterialNoAndOrderNo(data.getSupplierNo(),data.getMaterialNo(),data.getOrderNo());

        if(tbWmsMaterialDeliveryLines!=null&&tbWmsMaterialDeliveryLines.size()>0){

            OperationLog operationLog =new OperationLog();
            operationLog.setOperationType(ErrorType.ORDERIMPORT.getStatusName());
            operationLog.setErrorMsg("订单已经输入，不可重复输入 ");
            operationLog.setMethod("101");
            operationLog.setLocation(data.getOrderNo());
            operationLog.setId(idWorker.nextId() + "").preInsert(user != null ? user.getId() : ApiConstants.DEFAULT_USER_ID);
            if (user != null) {
                operationLog.setOperatorName(user.getUserName() + "(" + user.getNickName() + ")");
            }
            operationLogMapper.insert(operationLog);
            if(!StringUtils.isNull(errorMsg)){
                errorMsg =
                        errorMsg.concat(operationLog.getLocation().concat(operationLog.getErrorMsg()));
                // salesOrderItem.setImportErrorMesg(errorMsg);
                tbWmsMaterialDeliveryLine.setErrorFlag("Y");
            }else{
                // salesOrderItem.setImportErrorMesg(operationLog.getLocation().concat(operationLog.getErrorMsg()));
                errorMsg = "订单已经输入，不可重复输入 ";
                tbWmsMaterialDeliveryLine.setErrorFlag("Y");
            }
            itemErrorMsg = itemErrorMsg.concat(errorMsg);
            tbWmsMaterialDeliveryLine.setErrorCode("101");
            tbWmsMaterialDeliveryLine.setErrorFlag("Y");
        }


        Warehouse warehouse = this.tWhWarehouseMapper.findByCode(tbWmsMaterialDeliveryLine.getDeliveryWarehouseCode());
        if(warehouse!=null){
            tbWmsMaterialDeliveryLine.setDeliveryWarehouseType(warehouse.getWarehouseType());
            tbWmsMaterialDeliveryLine.setDestination
                    (warehouse.getProvince().concat(",").concat(warehouse.getCity()).concat(",")
                            .concat(warehouse.getDistrict()));
        }else{
            warehouse = new Warehouse();
            warehouse.setAddress(tbWmsMaterialDeliveryLine.getUnloadDockName());
            warehouse.setWarehouserCode(tbWmsMaterialDeliveryLine.getDeliveryWarehouseCode());
            warehouse.setWarehouserName(tbWmsMaterialDeliveryLine.getDeliveryWarehouseName());

            warehouse.setProvince("450000");
            warehouse.setCity("450200");
            warehouse.setCity("450202");
            if(tbWmsMaterialDeliveryLine.getDeliveryWarehouseCode().contains("LOC")){
                warehouse.setWarehouseType("总装");
            }else{
                warehouse.setWarehouseType("普通");
            }
            warehouse.setId(idWorker.nextId() + "").preInsert(user.getId());
            this.tWhWarehouseMapper.insert(warehouse);
        }
      Customer customer = this.customerMapper.selectById(user.getCustomerId());
        tbWmsMaterialDeliveryLine.setDeparture(customer.getLocationCode());
        tbWmsMaterialDeliveryLine.setOrderNo(tbWmsMaterialDelivery.getOrderNo());
        tbWmsMaterialDeliveryLine.setDeliveryId(tbWmsMaterialDelivery.getId());
        tbWmsMaterialDeliveryLine.setConsigneeAddress(data.getUnloadDockName());
        tbWmsMaterialDeliveryLine.setSite(user.getOrgId());
        TWhWarehouseCustomerMaterial tWhWarehouseCustomerMaterialVo =
                this.tWhWarehouseCustomerMaterialMapper.findBySkuCode(data.getMaterialNo());
        if(tWhWarehouseCustomerMaterialVo==null){
            String materialname= data.getMaterialNo();
            "客户物料没有维护".concat(materialname);
            throw new BusinessException(materialname);
        }else{
            tbWmsMaterialDeliveryLine.setInAndOutType(tWhWarehouseCustomerMaterialVo.getAttentionRemark());
            tbWmsMaterialDeliveryLine.setMaterialNo(tWhWarehouseCustomerMaterialVo.getMaterialNo());
        }
        String tWhWarehouseCustomerMaterialUpdateYnFlag = "N";

        tbWmsMaterialDeliveryLine.setSkuCode(data.getMaterialNo());

        if(!StringUtils.isNull(user.getCustomerId())){
            tbWmsMaterialDeliveryLine.setCompanyNo(user.getCustomerId());
        }else  if(!StringUtils.isNull(user.getSupplierId())){
            tbWmsMaterialDeliveryLine.setCompanyNo(user.getSupplierId());
        }else if(!StringUtils.isNull(user.getBaoliCompanyId())){
            tbWmsMaterialDeliveryLine.setCompanyNo(user.getBaoliCompanyId());
        }else if(!StringUtils.isNull(user.getStoreId())){
            tbWmsMaterialDeliveryLine.setCompanyNo(user.getStoreId());
        }else{
            tbWmsMaterialDeliveryLine.setCompanyNo(user.getOrgId());
        }
        if(data.getShipByPackOrqty()!=null){
            if(data.getShipByPackOrqty().equals("件")||data.getShipByPackOrqty().equals("箱")||data.getShipByPackOrqty().equals("桶")){
                tbWmsMaterialDeliveryLine.setMeasUnitNo(data.getShipByPackOrqty());
                tbWmsMaterialDeliveryLine.setShipByPackOrqty("pack");
            }else if(data.getShipByPackOrqty().equals("公斤")||data.getShipByPackOrqty().equals("吨")||data.getShipByPackOrqty().equals("千克")
                    ||data.getShipByPackOrqty().equals("斤")){
                tbWmsMaterialDeliveryLine.setMeasUnitNo(data.getShipByPackOrqty());
                tbWmsMaterialDeliveryLine.setShipByPackOrqty("weight");
            }else if(data.getShipByPackOrqty().equals("m3")||data.getShipByPackOrqty().equals("立方")||data.getShipByPackOrqty().equals("升")
                    ||data.getShipByPackOrqty().equals("毫升")){
                tbWmsMaterialDeliveryLine.setMeasUnitNo(data.getShipByPackOrqty());
                tbWmsMaterialDeliveryLine.setShipByPackOrqty("vol");
            }else {
                tbWmsMaterialDeliveryLine.setMeasUnitNo(data.getShipByPackOrqty());
                tbWmsMaterialDeliveryLine.setShipByPackOrqty("qty");
            }
            if(tWhWarehouseCustomerMaterialVo!=null){
            if(StringUtils.isNull(tWhWarehouseCustomerMaterialVo.getShipByPackOrqty())){
                tWhWarehouseCustomerMaterialVo.setShipByPackOrqty(tbWmsMaterialDeliveryLine.getShipByPackOrqty());
                tWhWarehouseCustomerMaterialUpdateYnFlag = "Y";
            }

              if(StringUtils.isNull(tWhWarehouseCustomerMaterialVo.getMeasUnitNo())){
                tWhWarehouseCustomerMaterialVo.setMeasUnitNo(tbWmsMaterialDeliveryLine.getMeasUnitNo());
                tWhWarehouseCustomerMaterialUpdateYnFlag = "Y";
              }
              if(tWhWarehouseCustomerMaterialUpdateYnFlag.equals("Y")){
               tWhWarehouseCustomerMaterialVo.preUpdate(user.getId());
               this.tWhWarehouseCustomerMaterialMapper.updateById(tWhWarehouseCustomerMaterialVo);
              }
            }

        }else{
            tbWmsMaterialDeliveryLine.setErrorFlag("Y");
            itemErrorMsg=itemErrorMsg.concat("发货单位为空 ");
            this.genOperationLog(tbWmsMaterialDeliveryLine,user);
        }

        if(StringUtils.isNull(data.getExcelQuantity())){
            if(!StringUtils.isNull(tbWmsMaterialDeliveryLine.getErrorCode())){
                tbWmsMaterialDeliveryLine.setErrorCode(tbWmsMaterialDeliveryLine.getErrorCode().concat(";").concat("103"));
            }else{
                tbWmsMaterialDeliveryLine.setErrorCode("103");
            }
            tbWmsMaterialDeliveryLine.setErrorFlag("Y");
            itemErrorMsg=itemErrorMsg.concat("销售件数为空 ");

            this.genOperationLog(tbWmsMaterialDeliveryLine,user);
        }else if(String.valueOf(data.getExcelQuantity()).contains(".")){
            if(!StringUtils.isNull(tbWmsMaterialDeliveryLine.getErrorCode()))
            {
                tbWmsMaterialDeliveryLine.setErrorCode(tbWmsMaterialDeliveryLine.getErrorCode().concat(";").concat("103"));
            }else{
                tbWmsMaterialDeliveryLine.setErrorCode("103");
            }
            tbWmsMaterialDeliveryLine.setErrorFlag("Y");
            itemErrorMsg=itemErrorMsg.concat("销售件数不是大于0的整数 ");

            this.genOperationLog(tbWmsMaterialDeliveryLine,user);
        }else if(Integer.valueOf(data.getExcelQuantity())<0) {
            if(!StringUtils.isNull(tbWmsMaterialDeliveryLine.getErrorCode())){
                tbWmsMaterialDeliveryLine.setErrorCode(tbWmsMaterialDeliveryLine.getErrorCode().concat(";").concat("103"));
            }else{
                tbWmsMaterialDeliveryLine.setErrorCode("103");
            }
            tbWmsMaterialDeliveryLine.setErrorFlag("Y");

            itemErrorMsg=itemErrorMsg.concat("入库件数不是大于0的整数 ");

            this.genOperationLog(tbWmsMaterialDeliveryLine,user);
        }else{
            tbWmsMaterialDeliveryLine.setQuantity(Double.valueOf(data.getExcelQuantity()));

        }
        if(StringUtils.isNull(data.getMaterialNo())){
            //||StringUtils.isNull(data.getCustSkuId())
            if(!StringUtils.isNull(tbWmsMaterialDeliveryLine.getErrorCode())){
                tbWmsMaterialDeliveryLine.setErrorCode(tbWmsMaterialDeliveryLine.getErrorCode().concat(";").concat("100"));
            }else{
                tbWmsMaterialDeliveryLine.setErrorCode("100");
            }
            tbWmsMaterialDeliveryLine.setErrorFlag("Y");
            itemErrorMsg = itemErrorMsg.concat("对方商品ID为空");

            this.genOperationLog(tbWmsMaterialDeliveryLine,user);
        }else{
            List<SkuVo> skus = this.skuMapper.findByCustSkuId(data.getMaterialNo(),data.getCustomerNo());
            if(skus!=null&&skus.size()>0){
                Spu spu = new Spu();

                spu.setCustSpuNo(data.getMaterialNo());
                spu.setSpuName(data.getMaterialName());
                spu.setStatus(SpuStatusEnum.CREATED.getEventCode());
                spu.setStoreId(data.getCustomerNo());
                spu.setSite(user.getSite());
                spu.setId(idWorker.nextId() + "").preInsert(user != null ? user.getId() : ApiConstants.DEFAULT_USER_ID);
                spuMapper.insert(spu);
                Sku sku = new Sku();
                sku.setSpuId(spu.getId());
                sku.setCustSkuId(data.getMaterialNo());
                sku.setSkuName(data.getMaterialName());
                sku.setStatus(SpuStatusEnum.CREATED.getEventCode());
                sku.setStoreId(data.getCustomerNo());
                sku.setSite(user.getSite());
                sku.setId(idWorker.nextId() + "").preInsert(user != null ? user.getId() : ApiConstants.DEFAULT_USER_ID);
                skuMapper.insert(sku);

            }
        }

        tbWmsMaterialDeliveryLine.setId(idWorker.nextId() + "").preInsert(user != null ? user.getId() : ApiConstants.DEFAULT_USER_ID);

        tbWmsMaterialDeliveryLine.setStatus(WmsOutStatusEnum.created.getValue());





        if(StringUtils.isNull(tbWmsMaterialDeliveryLine.getErrorFlag())){
            tbWmsMaterialDeliveryLine.setErrorFlag("N");
        }
        if(!StringUtils.isNull(data.getExeclCreateTime())){
            Date jobdt= DateUtils.parseDate(data.getCreateTime());
            tbWmsMaterialDeliveryLine.setCreateTime(jobdt);

        }else{
            tbWmsMaterialDeliveryLine.setCreateTime(null);
        }
        if(!StringUtils.isNull(data.getPublishTime())){
            Date jobdt= DateUtils.parseDate(data.getPublishTime());
            tbWmsMaterialDeliveryLine.setPublishTime(jobdt);

        }else{
            tbWmsMaterialDeliveryLine.setPublishTime(null);
        }
        if(!StringUtils.isNull(data.getRequestDeliveryTime())){
            Date jobdt= DateUtils.parseDate(data.getRequestDeliveryTime());
            tbWmsMaterialDeliveryLine.setRequestDeliveryTime(jobdt);

        }else{
            tbWmsMaterialDeliveryLine.setRequestDeliveryTime(null);
        }
        if(tbWmsMaterialDeliveryLine.getShipByPackOrqty().equals("pack")){
            if(tWhWarehouseCustomerMaterialVo.getUnitWeight()!=null){
                tbWmsMaterialDeliveryLine.setUnitWeight(tWhWarehouseCustomerMaterialVo.getUnitWeight());
                Double totwt = NumberUtils.mul
                        (tbWmsMaterialDeliveryLine.getQuantity(),tWhWarehouseCustomerMaterialVo.getUnitWeight().doubleValue());
                tbWmsMaterialDeliveryLine.setWeight(totwt);
            }else{
                tbWmsMaterialDeliveryLine.setWeight(tbWmsMaterialDeliveryLine.getQuantity());
            }
            if(tWhWarehouseCustomerMaterialVo.getUnitVolume()!=null){
                tbWmsMaterialDeliveryLine.setUnitVolume(tWhWarehouseCustomerMaterialVo.getUnitVolume());
                Double totvol = NumberUtils.mul
                        (tbWmsMaterialDeliveryLine.getQuantity(),tWhWarehouseCustomerMaterialVo.getUnitVolume().doubleValue());
                tbWmsMaterialDeliveryLine.setVolume(new BigDecimal(totvol));
            }else{
                tbWmsMaterialDeliveryLine.setVolume(new BigDecimal(tbWmsMaterialDeliveryLine.getQuantity()));
            }

        }else  if(tbWmsMaterialDeliveryLine.getShipByPackOrqty().equals("weight")){
            if(tWhWarehouseCustomerMaterialVo.getUnitWeight()!=null) {
                tbWmsMaterialDeliveryLine.setUnitWeight(tWhWarehouseCustomerMaterialVo.getUnitWeight());
                tbWmsMaterialDeliveryLine.setWeight(tbWmsMaterialDeliveryLine.getQuantity());
                Double qty = NumberUtils.div
                        (tbWmsMaterialDeliveryLine.getQuantity(),tWhWarehouseCustomerMaterialVo.getUnitWeight().doubleValue());
                tbWmsMaterialDeliveryLine.setQuantity(qty);
            }else{
                tbWmsMaterialDeliveryLine.setWeight(tbWmsMaterialDeliveryLine.getQuantity());
            }

            if(tWhWarehouseCustomerMaterialVo.getUnitVolume()!=null){
                tbWmsMaterialDeliveryLine.setUnitVolume(tWhWarehouseCustomerMaterialVo.getUnitVolume());
                Double qty = NumberUtils.div
                        (tbWmsMaterialDeliveryLine.getQuantity(),tWhWarehouseCustomerMaterialVo.getUnitVolume().doubleValue());
                tbWmsMaterialDeliveryLine.setVolume(new BigDecimal(tbWmsMaterialDeliveryLine.getQuantity()));
                tbWmsMaterialDeliveryLine.setQuantity(qty);
            }else{
                tbWmsMaterialDeliveryLine.setVolume(new BigDecimal(tbWmsMaterialDeliveryLine.getQuantity()));
            }


        }else  if(tbWmsMaterialDeliveryLine.getShipByPackOrqty().equals("volume")){
            if(tWhWarehouseCustomerMaterialVo.getUnitVolume()!=null){
                tbWmsMaterialDeliveryLine.setUnitVolume(tWhWarehouseCustomerMaterialVo.getUnitVolume());
                Double qty = NumberUtils.div
                        (tbWmsMaterialDeliveryLine.getVolume().doubleValue(),tWhWarehouseCustomerMaterialVo.getUnitVolume().doubleValue());
                tbWmsMaterialDeliveryLine.setVolume(tbWmsMaterialDeliveryLine.getVolume());
                tbWmsMaterialDeliveryLine.setQuantity(qty);
                if(tWhWarehouseCustomerMaterialVo.getUnitWeight()!=null){
                    tbWmsMaterialDeliveryLine.setUnitWeight(tWhWarehouseCustomerMaterialVo.getUnitWeight());
                    Double totwt = NumberUtils.mul
                            (qty,tWhWarehouseCustomerMaterialVo.getUnitWeight().doubleValue());

                    tbWmsMaterialDeliveryLine.setWeight(totwt);
                }
            }else{
                tbWmsMaterialDeliveryLine.setVolume(tbWmsMaterialDeliveryLine.getVolume());
            }

        }else{
            if(tWhWarehouseCustomerMaterialVo.getUnitWeight()!=null){
                tbWmsMaterialDeliveryLine.setUnitWeight(tWhWarehouseCustomerMaterialVo.getUnitWeight());
                Double wt = NumberUtils.mul(tbWmsMaterialDeliveryLine.getQuantity(),tWhWarehouseCustomerMaterialVo.getUnitWeight().doubleValue());
                tbWmsMaterialDeliveryLine.setWeight(wt);
            }
            if(tWhWarehouseCustomerMaterialVo.getUnitVolume()!=null){
                tbWmsMaterialDeliveryLine.setUnitVolume(tWhWarehouseCustomerMaterialVo.getUnitVolume());
                Double vol = NumberUtils.mul(tbWmsMaterialDeliveryLine.getQuantity(),tWhWarehouseCustomerMaterialVo.getUnitVolume().doubleValue());
                tbWmsMaterialDeliveryLine.setVolume(BigDecimal.valueOf(vol));
            }
        }
        tbWmsMaterialDeliveryLine.setImportErrorMesg(itemErrorMsg);

        //    try{
        if(StringUtils.isNull(tbWmsMaterialDeliveryLine.getErrorFlag())){
            tbWmsMaterialDeliveryLine.setId(idWorker.nextId() + "").preInsert(user != null ? user.getId() : ApiConstants.DEFAULT_USER_ID);

            if(!StringUtils.isNull(data.getExeclCreateTime())){
                Date createdate = DateUtils.parseDate(data.getExeclCreateTime());
                tbWmsMaterialDeliveryLine.setCreateTime(createdate);
            }
            if(!StringUtils.isNull(data.getExcelUpdateTime())){
                Date createdate = DateUtils.parseDate(data.getExcelUpdateTime());
                tbWmsMaterialDeliveryLine.setUpdateTime(createdate);
            }
            this.mapper.insert(tbWmsMaterialDeliveryLine);
            return tbWmsMaterialDeliveryLine;
        }else if(tbWmsMaterialDeliveryLine.getErrorFlag().equals("N")){
            tbWmsMaterialDeliveryLine.setId(idWorker.nextId() + "").preInsert(user != null ? user.getId() : ApiConstants.DEFAULT_USER_ID);

            if(!StringUtils.isNull(data.getExeclCreateTime())){
                Date createdate = DateUtils.parseDate(data.getExeclCreateTime());
                tbWmsMaterialDeliveryLine.setCreateTime(createdate);
            }
            if(!StringUtils.isNull(data.getExcelUpdateTime())){
                Date createdate = DateUtils.parseDate(data.getExcelUpdateTime());
                tbWmsMaterialDeliveryLine.setUpdateTime(createdate);
            }
            this.mapper.insert(tbWmsMaterialDeliveryLine);
            return tbWmsMaterialDeliveryLine;
        }else{
            return tbWmsMaterialDeliveryLine;
        }

        //   }catch(Exception e){
        //        log.error("addNewItem error:", e);
        //         log.error(ToStringBuilder.reflectionToString(data, ToStringStyle.JSON_STYLE));
        //      tbWmsMaterialDeliveryLine.setImportErrorMesg(e.getMessage().substring(0,49));
//            this.genOperationLog(tbWmsMaterialDeliveryLine,user);
        // }



    }
    @Transactional(readOnly = false)
    @Override
    public String calculateOutboundRate(){
        List<TbWmsMaterialDeliveryLineVo> skuCtOutBoundList = this.mapper.findSkuCtOutBoundList();
        UserVo sysUser = tokenService.getLoginUser(ServletUtils.getRequest()).getUser();
        for(int i=0;i<skuCtOutBoundList.size();i++){
            TbWmsMaterialDeliveryLineVo tbWmsMaterialDeliveryLineVo = (TbWmsMaterialDeliveryLineVo)skuCtOutBoundList.get(i);
            Sku sku = this.skuMapper.findBySkuCode(tbWmsMaterialDeliveryLineVo.getSkuCode());
            sku.setOutBoundFrequencyRate(i+1);
            sku.preUpdate(sysUser.getId());
            this.skuMapper.updateById(sku);
        }
        return "success";
    }
    @Transactional(readOnly = false)
    @Override
    public void refreshDeliveryPlanHead(String status,String id){
        int lineCt = this.mapper.ctLines(id);
        int sameStatusLines = this.mapper.sameStatusLines(status,id);
        UserVo sysUser = tokenService.getLoginUser(ServletUtils.getRequest()).getUser();

        if(lineCt==sameStatusLines){
            TbWmsMaterialDelivery entity = this.tbWmsMaterialDeliveryMapper.selectById(id);
            entity.setStatus(status);
            entity.preUpdate(sysUser.getId());
            this.tbWmsMaterialDeliveryMapper.updateById(entity);
        }
    }


    @Transactional(readOnly = false)
    @Override
    public void genOperationLog(TbWmsMaterialDeliveryLine data,UserVo user ) {
        OperationLog operationLog = new OperationLog();
        if(data.getErrorCode().equals("201")||data.getErrorCode().equals("601")){
            operationLog.setOperationType(ErrorType.ACCPROCESSIMPORT.getStatusName());
        }else{
            operationLog.setOperationType(ErrorType.ORDERIMPORT.getStatusName());
        }

        String errormsg = " ";

        if(!StringUtils.isNull(data.getImportErrorMesg())){
            errormsg = errormsg.concat(data.getImportErrorMesg());
        }
        operationLog.setErrorMsg(errormsg);
        operationLog.setMethod(data.getErrorCode());
        String orderNo = "子订单号: ".concat(data.getOrderNo());
        if(!StringUtils.isNull(data.getMaterialNo())){
            orderNo=orderNo.concat(" SPU: ").concat(data.getMaterialNo());
        }
        if(!StringUtils.isNull(data.getMaterialName())){
            orderNo=orderNo.concat(" 货物名称: ").concat(data.getMaterialName());
        }
        if(!StringUtils.isNull(data.getPublishTime())){
            orderNo=orderNo.concat(" 发布时间: ").concat(data.getPublishTime().toString());
        }
        if(!StringUtils.isNull(data.getSupplierName())){
            orderNo=orderNo.concat(" 供应商: ").concat(data.getSupplierName());
        }
        if(data.getQuantity()!=null){
            orderNo=orderNo.concat(" 数量: ").concat(String.valueOf(data.getQuantity()));
        }

        operationLog.setLocation(data.getCaseNo());
        operationLog.setId(idWorker.nextId() + "").preInsert(user != null ? user.getId() : ApiConstants.DEFAULT_USER_ID);
        if (user != null) {
            operationLog.setOperatorName(user.getUserName() + "(" + user.getNickName() + ")");
        }
        operationLogMapper.insert(operationLog);

    }
}
